package cn.wildfire.chat.app.extendsion.classes;

import android.content.Context;

import org.json.JSONObject;

import java.util.HashMap;

import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;

/**
 * Create by HEKE, 2019/8/16 17:32
 * TODO 检测用户是否存在封装对象
 */
public class UserCheckRequest {

    Context mContext;
    String userAccount;
    OnUserCheckResultListener onUserCheckResultListener;

    public UserCheckRequest(Context context, String userAccount, OnUserCheckResultListener onUserCheckResultListener) {
        mContext = context;
        this.userAccount = userAccount;
        this.onUserCheckResultListener = onUserCheckResultListener;
        check();
    }

    private void check() {
        try {
            HashMap<String, String> params = new HashMap<>();
            params.put("mobile", userAccount);
            OkHttpRequest.getInstance(mContext).requestAsyn(ServerUrlClient.FIND_USER, OkHttpRequest.TYPE_POST_JSON, params, new ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    try {
                        if (!TextUtils.isTextEmpty(result)) {
                            JSONObject jsonObject = new JSONObject(result);
                            String code = jsonObject.getString("code");
                            if (!TextUtils.isTextEmpty(code) && code.equals("0")) {
                                onUserCheckResultListener.result(true);
                            } else {
                                onUserCheckResultListener.result(false);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    if (onUserCheckResultListener != null) {
                        onUserCheckResultListener.result(false);
                    }
                }
            }).request();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnUserCheckResultListener {
        void result(boolean existed);
    }

}
